package BLL;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
 * @author 陈显彩
 * @version 2021.0601
 * @since 1.8
 */

/**
 * 文件相关时间
 */
public class FileTime {
    /**
     * 获取文件创建时间
     * @param filepath 文件路径
     * @return 格式化创建时间
     */
    public static String CreateTime(String filepath){
        Path path = Paths.get(filepath);
        BasicFileAttributes attributes;
        Date time = new Date();
        SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            attributes = Files.readAttributes(path, BasicFileAttributes.class);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(attributes.creationTime().toMillis());
            time = calendar.getTime();
        }catch(IOException e){
            e.printStackTrace();
        }
        return timeformat.format(time);
    }
    
    /**
     * 获取文件访问时间
     * @param filePath 文件路径
     * @return 格式化访问时间
     */
    public static String AccessTime(String filePath){
        File file = new File(filePath);
        Calendar cal = Calendar.getInstance();
        long time = file.lastModified();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(cal.getTime());
    }
    
    /**
     * 获取文件修改时间
     * @param filepath 文件路径
     * @return 格式化修改时间
     */
    public static String UpdateTime(String filepath){
        Path path = Paths.get(filepath);
        BasicFileAttributes attributes;
        Date time = new Date();
        SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            attributes = Files.readAttributes(path, BasicFileAttributes.class);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(attributes.lastModifiedTime().toMillis());
            time = calendar.getTime();
        }catch(IOException e){
            e.printStackTrace();
        }
        return timeformat.format(time);
    }
}
